<!--
 * @Description: 肯德基小料
 * @Author: Kerwin
 * @Date: 2025-05-08 16:19:21
 * @LastEditTime: 2025-08-04 16:59:46
 * @LastEditors:  Please set LastEditors
-->

<template>
  <view class="goodsChoose">
    <!-- 必选类 -->
    <view
      class="goodsSize1"
      v-if="goodsItem.required && goodsItem.required.length > 0"
    >
      <view class="goodsName">必选（已包含）</view>
      <view class="goodsItemDetail">
        <view
          class="required"
          v-for="(item, index) in goodsItem.required"
          :key="index"
        >
          <view class="img">
            <van-image
              class="img"
              height="100%"
              fit="contain"
              :src="item.product_img"
            />
            <!-- <van-image class="img" height="100%" fit="contain" :src="itemImg" /> -->
          </view>
          <view class="name">
            <!-- 麦辣鸡腿堡  麦辣鸡腿堡  麦辣鸡腿堡 -->
            <view> {{ item.product_name }}</view>
            <view> x {{ item.amount }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 可选类 -->
    <view
      class="optionalBox"
      v-if="goodsItem.optional && goodsItem.optional.length > 0"
    >
      <view
        class="optionalItem"
        v-for="(item, index) in goodsItem.optional"
        :key="item.id"
      >
        <view class="goodsName">{{ item.name }}(可选)</view>
        <view class="goodsItemDetail">
          <view
            class="optional"
            :class="{ activeOptional: goods.checked }"
            @click="handleOptionalClick(item, goods)"
            v-for="(goods, index) in item.sku_infos"
            :key="goods.id"
          >
            <view>
              <van-image
                class="img"
                height="100%"
                fit="contain"
                :src="goods.img"
              />
              <!-- <van-image class="img" height="100%" fit="contain" :src="itemImg" /> -->
            </view>
            <view class="name">
              <view> {{ goods.name }}</view>
              <view>
                <text
                  v-if="goods.price == null || goods.price == 0 ? false : true"
                >
                  +￥{{ goods.price }}</text
                >
                x {{ goods.amount }}</view
              >
            </view>
            <!-- 售罄蒙版 -->
            <view class="mode" v-if="goods.enable === false">
              <view class="mode-text">售罄</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 提示 -->
    <view class="mes">
      1．划线价格：商品展示的划横线的价格是参考价格，并非商品原价而是指不参加优惠的情况下，单品门店价格的总和（单品价总和）。当套餐内容可由您选择组合时，以套餐内可选商品的最低单价总和为为划线价，该价格仅供您参考。
      说明：
      2．非划线价格指参与优惠、使用抵扣券或代金券、在活动时间或满足活动条件、按照套餐组合购买的前提下可能支付的价格，具体的成交价格可能因参加其他活动等而发生变化，最终成交价格以订单结算页价格为准。
      3．产品及包装请以实物为准，图片仅供参考
    </view>
  </view>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  toRaw,
  toRefs,
  watch,
  nextTick
} from 'vue'
import itemImg from '@/static/xfl/item.png'
//props
const props = defineProps({
  product: {
    type: Object,
    default: {}
  },
  productChoose: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['chooseOptional'])
const goodsItem = ref()

// 点击事件选中了小料
const handleOptionalClick = (item: any, goods: any) => {
  if (!goods.enable)
    return uni.showToast({
      title: '该小料已售罄',
      icon: 'none'
    })
  goodsItem.value.optional.forEach((group: any) => {
    if (group.name === item.name) {
      group.sku_infos.forEach((ingredient: any) => {
        ingredient.checked = ingredient.id === goods.id
      })
    }
  })
  //   console.log('选中了其他的', goodsItem.value)
  // 触发计算并通知父组件
  const selectedIngredients = getSelectedIngredients()
  goodsItem.value.otherStr = selectedIngredients
  goodsItem.value.otherCheckStr =
    '/' +
    selectedIngredients
      .map((item) => {
        let str = ''
        if (Number(item.price) != 0) {
          str = item.name + `￥${item.price}`
        } else {
          str = item.name
        }
        return str
      })
      .join('/')
  console.log('选中了其他的selectedIngredients', goodsItem.value)
  //传给父组件
  emit('chooseOptional', goodsItem.value)
}

// 获取所有被选中的小料名称
const getSelectedIngredients = (): {
  price: string
  specificationId: string
  name: string
  skuId: string
}[] => {
  const selectedNames: {
    price: string
    specificationId: string
    name: string
    skuId: string
  }[] = []
  if (!goodsItem.value.optional) return selectedNames
  goodsItem.value.optional.forEach((group: any) => {
    group.sku_infos.forEach((ingredient: any) => {
      if (ingredient.checked) {
        selectedNames.push({
          specificationId: group.id,
          name: ingredient.name,
          skuId: ingredient.id,
          price: ingredient.price == null ? 0 : ingredient.price
        })
      }
    })
  })
  return selectedNames
}

// 初始化默认选中项
const initDefaultSelection = () => {
  const selectedIngredients = getSelectedIngredients()
  goodsItem.value.otherStr = selectedIngredients
  goodsItem.value.otherCheckStr =
    '/' +
    selectedIngredients
      .map((item) => {
        let str = ''
        if (Number(item.price) != 0) {
          str = item.name + `￥${item.price}`
        } else {
          str = item.name
        }
        return str
      })
      .join('/')
  emit('chooseOptional', goodsItem.value)
}

// 监听 product 变化，重新初始化
watch(
  () => props.product,
  (newVal) => {
    if (newVal) {
      goodsItem.value = JSON.parse(JSON.stringify(newVal))
      initDefaultSelection()
    }
  },
  { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
.goodsChoose {
  // height: calc(100vh - 400rpx);
  // margin-bottom: 1300rpx;
  background-color: #fff;
}

.goodsSize1 {
  .goodsItemDetail {
    display: flex;
    flex-wrap: wrap;

    .required {
      width: 200rpx;
      // height: 160rpx;
      border-radius: 10rpx;
      text-align: center;
      // margin: 30rpx;
      // margin-bottom: 80rpx;
      padding: 5rpx;
      // border: 2rpx solid #f1f1f1;

      .img {
        height: 160rpx;
      }

      .name {
        font-size: 24rpx;
      }
    }
  }

  .goodsSize1_1 {
    font-weight: 700;
    margin: 40rpx 0;
  }

  .goodsSize1_2 {
    margin-bottom: 40rpx;
  }
}

.optionalBox {
  .optionalItem {
    .goodsItemDetail {
      display: flex;
      flex-wrap: wrap;

      .optional {
        position: relative;
        width: 150rpx;
        // height: 160rpx;
        // border: 2rpx solid #f1f1f1;
        border-radius: 10rpx;
        text-align: center;
        margin: 30rpx;
        // margin-bottom: 80rpx;
        background-color: #fff;

        .mode {
          position: absolute;
          top: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(25, 14, 14, 0.4);

          .mode-text {
            color: #e9e9e9;
          }
        }

        .name {
          font-size: 24rpx;
        }
      }
    }
  }
}

.goodsName {
  font-size: 28rpx;
  // color: #969696;
  color: #333;
  font-weight: 700;
  margin: 20rpx 0;
}

.mes {
  height: 500rpx;
  font-size: 20rpx;
  color: #969696;
  margin-top: 50rpx;
}

//选中了小料
.activeOptional {
  // border: 20rpx solid #ff6c18 !important;
  // background-color: rgb(255, 108, 24, 0.2) !important;
  background-color: rgba(243, 243, 243, 0.95) !important;
  /* 蓝色半透明蒙版 */
  //   opacity: 0.8; /* 可选：整体透明度控制 */
}
</style>
